import { createApp } from 'vue/dist/vue.esm-bundler.js'

export default (app) => {
  const g = app.config.globalProperties

  const showSysDialog = (msg, cfg = {}) => {
    const app_ = createApp({
      template: `
        <div class="sys-dialog sys-dialog-${ cfg.type || 'alert' }">
          <div class="inner">
            <div class="sys-dialog-msg">${ msg }</div>
            <div class="sys-dialog-ctrl">
              <button tabindex="-1" class="btn btn-default btn-cancel"
                @click="cmd('取消')"
                v-if="cfg.type === 'confirm'"
              >取消</button>
              <button tabindex="-1" class="btn btn-primary btn-confirm"
                @click="cmd('确定')"
              >确定</button>
            </div>
          </div>
        </div>
      `,
      data() {
        return { cfg }
      },
      methods: {
        cmd(a) {
          switch (a) {
            case '取消': reject(); this.close(); break;
            case '确定': resolve(); this.close(); break;
          }
        },
        close() {
          app_.unmount()
        }
      }
    })

    const vm_ = app_.mount(document.createElement('div'))
    document.body.appendChild(vm_.$el)

    let resolve, reject
    return new Promise((resolve_, reject_) => {
      resolve = resolve_
      reject = reject_
    })
  }

  g.alert = (msg) => {
    return showSysDialog(msg, { type: 'alert' })
  }
  g.confirm = (msg) => {
    return showSysDialog(msg, { type: 'confirm' })
  }
}
